<template>
  <t-drawer
    :visible="visible"
    :header="drawerTitle"
    size="50%"
    placement="right"
    @close="handleClose"
  >
    <!-- 抽屉内容区域 -->
    <div class="goods-drawer-body">
      <t-form
        ref="goodsForm"
        :data="formData"
        :rules="formRules"
        label-align="right"
        label-width="120px"
        class="goods-form"
      >
        <!-- 商品名称 -->
        <t-form-item label="商品名称" name="name">
          <t-input
            v-model="formData.name"
            placeholder="请输入商品名称"
            maxlength="100"
          />
        </t-form-item>

        <!-- 兑换积分 -->
        <t-form-item label="兑换积分" name="price">
          <t-input-number
            v-model="formData.price"
            placeholder="请输入兑换所需积分"
            :min="0"
            :max="999999"
          />
        </t-form-item>

        <!-- 商品简介 -->
        <t-form-item label="商品简介" name="description">
          <t-textarea
            v-model="formData.description"
            placeholder="请输入商品简介"
            :maxlength="500"
            :autosize="{ minRows: 3, maxRows: 6 }"
          />
        </t-form-item>

        <!-- 商品图片 -->
        <t-form-item label="商品图片" name="image">
          <div style="display: flex; flex-direction: column; width: 100%;">
            <!-- 文件上传 -->
            <t-upload
              :action="uploadAction"
              :accept="'image/*'"
              :size-limit="{ size: 10, unit: 'MB' }"
              :format-response="formatImageResponse"
              :on-success="handleImageSuccess"
              :on-fail="handleUploadFail"
              @waiting-upload-files-change="handleImageProgress"
              :draggable="true"
              :show-upload-list="false"
              :auto-upload="true"
              :disabled="imageUploading"
              theme="custom"
              tips="支持拖拽上传，单个文件不超过10MB，建议尺寸800x800px"
              style="width: 100%; margin-bottom: 8px;"
            >
              <template #drag-content>
                <div v-loading="imageUploading" class="upload-drag-content">
                  <template>
                    <t-icon name="cloud-upload" size="36px" />
                    <div class="upload-text">
                      <p>点击上传图片或将图片拖拽到此区域</p>
                      <p class="upload-tips">支持 JPG、PNG、GIF 格式，单个文件不超过10MB</p>
                    </div>
                  </template>
                </div>
              </template>
            </t-upload>

            <!-- 图片预览 -->
            <div v-if="formData.image" class="image-preview">
              <img :src="formData.image" :alt="formData.name" class="preview-image" />
              <div class="image-actions">
                <t-button theme="danger" variant="text" size="small" @click="removeImage">
                  <template #icon><t-icon name="delete" /></template>
                  删除图片
                </t-button>
              </div>
            </div>
          </div>
        </t-form-item>
      </t-form>
    </div>

    <!-- 底部按钮区域 -->
    <template #footer>
      <div class="drawer-footer">
        <t-button variant="outline" theme="default" @click="handleCancel">
          取消
        </t-button>
        <t-button theme="primary" @click="handleConfirm" :loading="submitLoading">
          确定
        </t-button>
      </div>
    </template>
  </t-drawer>
</template>

<script>
import { addGoods, updateGoods } from '@/api/goods';

export default {
  name: 'GoodsDrawer',
  model: {
    prop: 'visible',
    event: 'update:visible',
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 当前编辑的商品数据（有 id 表示编辑，无 id 表示新增）
    goodsData: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      formData: {
        id: null,
        name: '',
        price: 0,
        description: '',
        image: '',
      },
      formRules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { max: 100, message: '商品名称不能超过100个字符', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入兑换积分', trigger: 'blur' },
          { type: 'number', message: '兑换积分必须为数字', trigger: 'blur' },
          { min: 0, message: '兑换积分不能小于0', trigger: 'blur' },
        ],
        description: [
          { required: true, message: '请输入商品简介', trigger: 'blur' },
          { max: 500, message: '商品简介不能超过500个字符', trigger: 'blur' },
        ],
        image: [
          { required: true, message: '请上传商品图片', trigger: 'blur' },
        ],
      },
      uploadAction: '/api/cms/tools/upload', // 上传接口地址
      imageUploading: false,
      submitLoading: false,
    };
  },
  computed: {
    drawerTitle() {
      return this.goodsData?.id ? '编辑商品' : '添加商品';
    },
    isEdit() {
      return !!this.goodsData?.id;
    },
  },
  watch: {
    visible: {
      handler(newVal) {
        if (newVal) {
          this.initFormData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 初始化表单数据
    initFormData() {
      if (this.isEdit) {
        this.formData = {
          id: this.goodsData.id,
          name: this.goodsData.name || '',
          price: this.goodsData.price || 0,
          description: this.goodsData.description || '',
          image: this.goodsData.image || '',
        };
      } else {
        this.resetForm();
      }
    },

    // 重置表单
    resetForm() {
      this.formData = {
        id: null,
        name: '',
        price: 0,
        description: '',
        image: '',
      };
      this.$nextTick(() => {
        this.$refs.goodsForm?.clearValidate();
      });
    },

    // 处理图片上传进度
    handleImageProgress() {
      this.imageUploading = true;
    },

    // 格式化图片上传响应
    formatImageResponse(res) {
      return {
        url: res.data?.url || '',
        error: !res.data?.url,
      };
    },

    // 处理图片上传成功
    handleImageSuccess(response) {
      this.imageUploading = false;
      const url = response.response?.url ?? '';
      if (url) {
        this.formData.image = url;
        this.$message.success('图片上传成功');
      }
    },

    // 处理上传失败
    handleUploadFail(error) {
      this.imageUploading = false;
      console.error('上传失败:', error);
      this.$message.error('图片上传失败，请重试');
    },

    // 移除图片
    removeImage() {
      this.formData.image = '';
    },

    // 取消操作
    handleCancel() {
      this.handleClose();
    },

    // 关闭抽屉
    handleClose() {
      this.resetForm();
      this.$emit('update:visible', false);
    },

    // 确认提交
    async handleConfirm() {
      try {
        const valid = await this.$refs.goodsForm.validate();

        if (valid !== true) {
          return;
        }

        this.submitLoading = true;

        // 准备提交数据
        const submitData = {
          name: this.formData.name,
          description: this.formData.description,
          price: this.formData.price,
          image: this.formData.image,
        };

        let result;
        // 根据是否有id判断是新增还是编辑
        if (this.isEdit) {
          // 编辑商品
          result = await updateGoods(this.formData.id, submitData);
        } else {
          // 新增商品
          result = await addGoods(submitData);
        }

        if (result) {
          this.$message.success(this.isEdit ? '编辑成功' : '添加成功');
          this.$emit('success', this.formData);
          this.handleClose();
        }
      } catch (error) {
        console.error('提交失败:', error);
        this.$message.error(error.message || '操作失败，请重试');
      } finally {
        this.submitLoading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.goods-drawer-body {
  padding: 20px;
  height: 100%;
  overflow-y: auto;

	/deep/ .t-upload__dragger {
		width: 100%;
		overflow: hidden;
	}
}

.upload-drag-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  text-align: center;
  transition: all 0.3s ease;

  &.uploading {
    background-color: #f0f8ff;
    border-color: #1890ff;
  }

  .upload-text {
    margin-top: 12px;
    width: 100%;

    p {
      margin: 8px 0;

      &.upload-tips {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.image-preview {
  margin-top: 16px;
  border: 1px solid #e7e7e7;
  border-radius: 8px;
  overflow: hidden;

  .preview-image {
    width: 100%;
    max-height: 300px;
    object-fit: contain;
  }

  .image-actions {
    display: flex;
    justify-content: flex-end;
    padding: 8px;
    background-color: #f8f9fa;
  }
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>